<!-- <title>瑞众银保“五个一”功成---营业部经理月度计划<title> -->
<style lang="less" scoped>
@import '@css/list.less';
</style>
<template>
  <div id="app">
    <van-sticky>
      <div class="title">获取图片信息</div>
    </van-sticky>
    <van-form @submit="onsaveEachForm">
      <van-cell-group inset>
        <van-field
          name="uploader"
          label="上传图片"
          :rules="[{ required: true, message: '请上传不超过1张照片,5M以内' }]"
        >
          <template #input>
            <van-uploader
              v-model="uploaderImgList"
              :max-count="1"
              :before-read="onbeforeRead"
              :after-read="onafterRead"
            ></van-uploader>
          </template>
        </van-field>
      </van-cell-group>
      <van-cell-group inset>
        <van-cell-group title="日期">
          <van-cell v-for="(date, index) in dates" :key="index" :title="index" :value="date" />
        </van-cell-group>
        <van-cell-group title="地点">
          <van-cell
            v-for="(location, index) in locations"
            :key="index"
            :title="index"
            :value="location"
          />
        </van-cell-group>
        <van-cell-group title="人数">
          <van-cell title="人数" :value="faceCount" />
        </van-cell-group>
      </van-cell-group>
      <div class="button">
        <van-button block type="primary" native-type="submit" style="width: 55%">保存</van-button>
      </div>
    </van-form>
  </div>
</template>
<script setup>
import {
  onBeforeMount,
  onMounted,
  onUnmounted,
  watch,
  computed,
  provide,
  inject,
  ref,
  reactive,
  nextTick,
  h
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
const dayjs = inject('$dayjs')
const showPageLoading = inject('showPageLoading')
const hidePageLoading = inject('hidePageLoading')
const showAllNonBaseMenuItem = inject('showAllNonBaseMenuItem')
const hideAllNonBaseMenuItem = inject('hideAllNonBaseMenuItem')
import { isIOS, parseTime, handleFontSize } from '@/utils'
import {
  saveAnalyzeImageInfoUsingPOST,
  gdrzapiUpload,
  getNumberOfParticipants
} from '@/request/api.js'
import Vconsole from 'vconsole'
let vConsole = new Vconsole()
onMounted(() => {
  agentcode = route.query.agentcode
})
let agentcode

const uploaderImgList = ref([])

import { compressImageToTargetSize } from '@/utils'
import { showToast } from 'vant'
const targetSize = 1024 * 1024 * 1 // 1M大小
function onbeforeRead(file) {
  return new Promise((resolve, reject) => {
    console.log('压缩前文件大小:', file.size / (1024 * 1024), 'M')
    if (file.size < targetSize) {
      console.log('小于，不用压缩')
      resolve(file)
    } else {
      compressImageToTargetSize(file, targetSize).then((res) => {
        console.log('压缩后的文件大小:', res.size / (1024 * 1024), 'M')
        resolve(res)
      })
    }
  })
}
//文件读取后的回调函数
function onafterRead(file) {
  console.log('读取完毕')
  onGetNumberOfParticipants()
}
const imgUrlsList = ref([])
//分析图片信息
const allTexts = ref() // 所有文字
const dates = ref() // 所有日期
const faceCount = ref() // 人数
const locations = ref() // 所有地点
function onGetNumberOfParticipants() {
  // 循环list把单个图片上传
  // 创建包含所有请求的promise数组
  const promises = uploaderImgList.value.map(async (file) => {
    try {
      let Form = new FormData()
      Form.append('file', file.file)
      const imgUrlRes = await gdrzapiUpload(Form)
      return imgUrlRes.code == 200 ? imgUrlRes.data : null
    } catch (error) {
      return null
    }
  })
  // 等待所有请求完成
  Promise.all(promises)
    .then((results) => {
      imgUrlsList.value = results.filter((res) => res !== null)
      // 单个图片上传完毕，统一提交数据
      showPageLoading('分析中...')
      const imageUrl = {
        imageUrl: `https://gdinfo.ruiinsurance.com/${imgUrlsList.value[0]}`
      }
      getNumberOfParticipants(JSON.stringify(imageUrl))
        .then((res) => {
          if (res.success == true) {
            allTexts.value = res.allTexts // 所有文字
            dates.value = res.dates // 所有日期
            faceCount.value = res.faceCount // 人数
            locations.value = res.locations // 所有地点
            showToast('分析成功')
          } else {
            showDialog({
              message: '图片分析失败，请重试'
            }).then(() => {
              uploaderImgList.value = []
            })
          }
        })
        .finally(() => {
          hidePageLoading()
        })
    })
    .catch((error) => {
      showDialog({
        message: '图片上传失败，请重试'
      }).then(() => {
        uploaderImgList.value = []
      })
    })
    .finally(() => {
      hidePageLoading()
    })
}
function onsaveEachForm() {
  showPageLoading('保存中')
  saveAnalyzeImageInfoUsingPOST({
    agentcode: agentcode,
    allTexts: allTexts.value,
    dates: dates.value,
    faceCount: faceCount.value,
    locations: locations.value,
    url: `https://gdinfo.ruiinsurance.com/${imgUrlsList.value[0]}`
  })
    .then((res) => {
      if (res.status == 0) {
        hidePageLoading()
        showDialog({
          title: '保存成功'
        }).then(() => {})
      } else {
        showDialog({
          message: '保存失败，请重试'
        }).then(() => {
          uploaderImgList.value = []
        })
      }
    })
    .finally(() => {
      hidePageLoading()
    })
}
</script>
